package com.doupi.partner.manager.authenticator.util;

import com.doupi.partner.util.SpringContextUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.SimpleByteSource;

/**
 * shiro密码工具
 * 
 * @author Super Jens Wang
 * @version 1.0 on 2017/4/3 上午5:46.
 */
public class PasswordUtils {
	private static HashedCredentialsMatcher credentialsMatcher = null;
	private static final String DEFAULT_SALT_STRING = "ABCDEFGHIJKLMNOPQRSTUVYXWZabcdefghijklmnopqrstuvyxwz1234567890!@#$%^&*()-+?:;,.><";

	/**
	 * 对原始密码加密
	 * 
	 * @param originPassword
	 *            原始密码
	 * @param salt
	 *            盐
	 * @return 加密后的密码
	 */
	public static String encryptPassword(String originPassword, String salt) {
		HashedCredentialsMatcher credentialsMatcher = getCredentialsMatcher();
		Hash hash = new SimpleHash(credentialsMatcher.getHashAlgorithmName(), originPassword, new SimpleByteSource(salt), credentialsMatcher.getHashIterations());
		return hash.toString();
	}

	/**
	 * 随机生成8位数字盐
	 * 
	 * @return 盐字符串
	 */
	public static String generatePasswordSalt() {
		return RandomStringUtils.random(8, DEFAULT_SALT_STRING);
	}

	/**
	 * 获取密码加密工具
	 * 
	 * @return 加密工具
	 */
	private static HashedCredentialsMatcher getCredentialsMatcher() {
		if (null == credentialsMatcher) {
			credentialsMatcher = SpringContextUtils.getBeanByName("credentialsMatcher");
		}
		return credentialsMatcher;
	}
}
